<script setup>
import ImageUpload from "@/common/ImageUpload.vue";
import {onMounted, ref} from "vue";
import {addAdmin, getAdminById, updateAdmin} from "@/api/admin.js";
import {ElMessage} from "element-plus";
//有id是编辑，没有id是添加
const {id} = defineProps({
  id: {
    type: Number,
    default: undefined
  },
})

onMounted(() => {
  if (id !== undefined) {
    getAdminInfo(id)
  }
})
//获取管理员信息
const getAdminInfo = async (id) => {
  const {code, data, msg} = await getAdminById(id);
  if (code !== 200) {
    ElMessage({
      type: 'error',
      message: msg,
    })
    window.location.reload();
    return
  }
  form.value = data
}
//表单
const form = ref({
  id: undefined,
  account: undefined,
  password: undefined,
  nickname: undefined,
  avatar: undefined,
  superAdmin: undefined,
  status: undefined,
})
//提交表单
const onSubmit = async () => {
  if (id === undefined) {
    await add()
  } else {
    await edit(id)
  }
}
const emit = defineEmits(['success'])
//添加管理员
const add = async () => {
  const {code, msg} = await addAdmin(form.value);
  if (code !== 200) {
    ElMessage.error(msg)
    return
  }
  ElMessage.success(msg)
  emit('success')
}
//修改管理员
const edit = async () => {
  const {code, msg} = await updateAdmin(form.value);
  if (code !== 200) {
    ElMessage.error(msg)
    return
  }
  ElMessage.success(msg)
  emit('success')
}
</script>


<template>
  <el-form label-width="100px">
    <el-form-item required label="账号">
      <el-input placeholder="请输入账号" :disabled="id !== undefined" clearable v-model="form.account"/>
    </el-form-item>
    <el-form-item required label="密码" v-if="id !== 1">
      <el-input type="password" clearable show-password
                :placeholder="id === undefined ? '请输入密码' : '不输入不会更改'" v-model.trim="form.password"/>
    </el-form-item>
    <el-form-item required label="昵称">
      <el-input placeholder="请输入昵称" clearable v-model="form.nickname"/>
    </el-form-item>
    <el-form-item required label="状态" v-if="id !== undefined">
      <el-switch :active-value="1" :inactive-value="0" v-model="form.status"></el-switch>
    </el-form-item>
    <el-form-item required label="头像">
      <image-upload v-model:url="form.avatar"/>
    </el-form-item>
    <el-form-item required label="超级管理员">
      <el-switch :active-value="1" :inactive-value="0" v-model="form.superAdmin"></el-switch>
    </el-form-item>
  </el-form>
  <div style="text-align: right; margin-top: 20px">
    <el-button type="primary" @click="onSubmit">提交</el-button>
  </div>

</template>

<style scoped lang="scss">

</style>